package hong.jun.basic.util;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import hong.jun.pet_home.domain.pay.AlipayInfo;
import hong.jun.pet_home.domain.pay.PayBill;
import hong.jun.pet_home.domain.util.SmsConstants;

import java.math.BigDecimal;

public class AlipayUtils {

    public static String sendPayRequest(AlipayInfo alipayInfo, PayBill payBill) {
        try {
            //获得初始化的AlipayClient
            //参数是支付宝验证网址 和 Appid
            AlipayClient alipayClient = new DefaultAlipayClient(SmsConstants.GATEWAY_URL, alipayInfo.getAppid(),
                    alipayInfo.getMerchant_private_key(),
                    "json", SmsConstants.CHARSET, alipayInfo.getAlipay_public_key(), SmsConstants.SIGN_TYPE);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(SmsConstants.RETURN_URL);//跳转商家网页
            alipayRequest.setNotifyUrl(SmsConstants.NOTIFY_URL);//回调信息发送地址

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = new String(payBill.getUnionPaySn());
            //付款金额，必填
            BigDecimal money = payBill.getMoney();

            //yhptest的注释 从分转换为元
            money = money.divide(new BigDecimal(100));
            System.out.println(money.toString());
            String total_amount = new String(money.toString());
            //订单名称，必填
            String subject = new String("宠物乐园订单！");
            //商品描述，可空
            String body = new String(payBill.getDigest());

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "支付请求失败";
        }
    }
}
